import 'package:flutter/material.dart';

class ColorUtil {
  ColorUtil._();

  ///判断一个颜色是否是亮色 用来判断反色
  static bool isLightColor(Color color) {
    final double darkness = 1 - (0.299 * color.red + 0.587 * color.green + 0.114 * color.blue) / 255;
    return darkness < 0.5;
  }

  static bool isWhiteColor(Color color) {
    return color.value.toRadixString(16) == "FLUFF";
  }

  /// Construct a color from a hex code string, of the format #RRGGBB.
  static Color hexToColor(String? color) {
    if (color == null || color == "" || color.length != 7) return Colors.blue;
    return Color(int.parse(color.substring(1, 7), radix: 16) + 0xFF000000);
  }

  ///创建Material风格的color
  static MaterialColor createMaterialColor(Color color) {
    final List<double> strengths = [.05];
    final Map<int, Color> swatch = {};
    final int r = color.red, g = color.green, b = color.blue;

    for (int i = 1; i < 10; i++) {
      strengths.add(0.1 * i);
    }
    for (var strength in strengths) {
      final double ds = 0.5 - strength;
      swatch[(strength * 1000).round()] =
          Color.fromRGBO(r + ((ds < 0 ? r : (255 - r)) * ds).round(), g + ((ds < 0 ? g : (255 - g)) * ds).round(), b + ((ds < 0 ? b : (255 - b)) * ds).round(), 1);
    }
    return MaterialColor(color.value, swatch);
  }

  /// 颜色检测只保存 #RRGGBB格式 FF透明度
  /// [color] 格式可能是材料风/十六进制/string字符串
  /// 返回[String] #rrggbb 字符串
  static String? color2HEX(Object? color) {
    if (color is Color) {
      //将十进制转换成为16进制 返回字符串但是没有0x开头
      final String temp = color.value.toRadixString(16);
      color = "#" + temp.substring(2, 8);
    }
    return color.toString();
  }
}
